// 简化的protobuf JavaScript实现
// 这里我们使用一个简化的实现来支持基本的protobuf消息

class ProtobufMessage {
    constructor() {
        this.base = {
            type: 0,
            timestamp: Date.now(),
            from: '',
            room_id: ''
        };
        this.payload = null;
    }

    // 设置基础消息
    setBase(type, from, roomId) {
        this.base = {
            type: type,
            timestamp: Date.now(),
            from: from,
            room_id: roomId
        };
    }

    // 设置加入游戏消息
    setJoinGame(player) {
        this.payload = {
            type: 'join_game',
            player: player
        };
    }

    // 设置离开游戏消息
    setLeaveGame(player) {
        this.payload = {
            type: 'leave_game',
            player: player
        };
    }

    // 设置更新玩家消息
    setUpdatePlayer(player) {
        this.payload = {
            type: 'update_player',
            player: player
        };
    }

    // 设置表情包消息
    setEmojiSent(emoji, username, playerId) {
        this.payload = {
            type: 'emoji_sent',
            emoji: emoji,
            username: username,
            player_id: playerId
        };
    }

    // 设置心跳消息
    setHeartbeat() {
        this.payload = {
            type: 'heartbeat',
            timestamp: Date.now()
        };
    }

    // 序列化为JSON字符串（用于WebSocket发送）
    toJSON() {
        return JSON.stringify({
            base: this.base,
            payload: this.payload
        });
    }

    // 从JSON字符串反序列化
    static fromJSON(jsonString) {
        try {
            const data = JSON.parse(jsonString);
            const message = new ProtobufMessage();
            message.base = data.base;
            message.payload = data.payload;
            return message;
        } catch (e) {
            console.error('解析protobuf消息失败:', e);
            return null;
        }
    }

    // 获取消息类型
    getType() {
        return this.base.type;
    }

    // 获取发送者
    getFrom() {
        return this.base.from;
    }

    // 获取房间ID
    getRoomId() {
        return this.base.room_id;
    }

    // 获取负载数据
    getPayload() {
        return this.payload;
    }
}

// 消息类型枚举
const MessageType = {
    LOGIN_REQUEST: 0,
    LOGIN_RESPONSE: 1,
    LOGOUT_REQUEST: 2,
    LOGOUT_RESPONSE: 3,
    JOIN_GAME: 4,
    LEAVE_GAME: 5,
    UPDATE_PLAYER: 6,
    EMOJI_SENT: 7,
    ROOM_UPDATE: 8,
    PLAYER_MOVE: 9,
    ERROR: 10,
    HEARTBEAT: 11
};

// 导出到全局作用域
window.ProtobufMessage = ProtobufMessage;
window.MessageType = MessageType;

